package cn.xuqiudong.console.module.system.service;

import cn.xuqiudong.common.base.service.BaseService;
import cn.xuqiudong.common.util.collections.CalcDiffCollection;
import cn.xuqiudong.console.module.system.mapper.SysRoleMapper;
import cn.xuqiudong.console.module.system.model.SysMenu;
import cn.xuqiudong.console.module.system.model.SysRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述:角色表 Service
 * @author Vic.xu
 * @since  2019-58-29 08:58
 */
@Service
public class SysRoleService extends BaseService<SysRoleMapper, SysRole> {

    /**
     * 数字正则
     */
    private static final String NUMBER_REG = "(\\d|\\d+,|\\d+,\\d+)+";

    /**
     * 全部菜单:选中当前角色拥有的
     * @param id
     * @return
     */
    public List<SysMenu> roleMenus(Integer id) {
        return mapper.roleMenus(id);
    }

    public static void main(String[] args) {
        List<Integer> curMenuIds = Arrays.asList("3,2,1".split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
        curMenuIds.forEach(System.out::println);
    }

    /**
     * 保存角色 以及角色关联的菜单
     * @param entity
     * @param menuIds
     */
    @Transient
    public void save(SysRole entity, String menuIds) {
        super.save(entity);
        Integer roleId = entity.getId();
        //保存角色对应的菜单
        if (StringUtils.isNotBlank(menuIds) && menuIds.matches(NUMBER_REG)) {
            List<Integer> curMenuIds = Arrays.asList(menuIds.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
            List<Integer> oldMenuIds = mapper.roleMenuIds(entity.getId());
            //构建两个集合的差别:
            CalcDiffCollection<Integer> calc = CalcDiffCollection.instance(oldMenuIds, curMenuIds);

            List<Integer> addMenuIds = calc.getOnlyInNew();
            List<Integer> delMenuIds = calc.getOnlyInOld();
            //新增角色和菜单关联
            if (!addMenuIds.isEmpty()) {
                mapper.addRoleMenu(roleId, addMenuIds);
            }
            //删除角色和菜单关联
            if (!delMenuIds.isEmpty()) {
                mapper.deleteRoleMenu(roleId, delMenuIds);
            }
        } else {
            // 通过角色id删除角色和菜单的关系
            mapper.deleteRoleMenuByRoleId(roleId);
        }


    }

    @Override
    protected boolean hasAttachment() {
        return false;
    }

}
